<template>
  <view class="container">
    <view class="example">
      <uni-forms ref="form" :model="user" labelWidth="80px">
        <uni-forms-item label="账号">
          <uni-easyinput v-model="account" placeholder="账号" :disabled="true"/>
        </uni-forms-item>
        <uni-forms-item label="用户姓名" name="name">
          <uni-easyinput v-model="user.name" placeholder="请输入姓名" :disabled="true"/>
        </uni-forms-item>
        <uni-forms-item label="手机号码" name="phone">
          <uni-easyinput v-model="user.phone" placeholder="请输入手机号码"/>
        </uni-forms-item>
        <uni-forms-item label="身份证" name="identityCard">
          <uni-easyinput v-model="user.identityCard" placeholder="请输入身份证"/>
        </uni-forms-item>
        <!-- <uni-forms-item label="邮箱" name="email">
          <uni-easyinput v-model="user.email" placeholder="请输入邮箱" />
        </uni-forms-item> -->
        <uni-forms-item label="性别" name="sex">
          <uni-data-checkbox v-model="user.sex" :localdata="sexs"/>
        </uni-forms-item>
        <uni-forms-item label="出生日期" name="dateOfBirth">
          <uni-datetime-picker type="date" :clear-icon="false" v-model="user.dateOfBirth"
                               @maskClick="maskClick"/>
        </uni-forms-item>
        <uni-forms-item label="民族" name="nation">
          <uni-data-select v-model="user.nation" :localdata="nationList"
                           placeholder="请选择民族">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="籍贯" name="nativePlace">
          <uni-easyinput v-model="user.nativePlace" placeholder="请输入籍贯"/>
        </uni-forms-item>
        <uni-forms-item label="毕业学校" name="schoolTag">
          <uni-easyinput v-model="user.schoolTag" placeholder="请输入毕业学校"/>
        </uni-forms-item>
        <uni-forms-item label="学历" name="education">
          <uni-data-select v-model="user.education" :localdata="educationList"
                           placeholder="请选择学历">
          </uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="学科" name="teachSubjects">
          <uni-easyinput v-model="user.teachSubjects" placeholder="请输入学科"/>
        </uni-forms-item>
        <uni-forms-item label="职称" name="professionalTitle">
          <uni-easyinput v-model="user.professionalTitle" placeholder="请输入职称"/>
        </uni-forms-item>
        <uni-forms-item label="单位名称" name="companyName">
          <uni-easyinput v-model="user.companyName" placeholder="请输入单位名称"/>
        </uni-forms-item>
        <uni-forms-item label="政治面貌" name="partyGroupings">
          <uni-easyinput v-model="user.partyGroupings" placeholder="请输入政治面貌"/>
        </uni-forms-item>
        <uni-forms-item label="职务" name="jobTitle">
          <uni-easyinput v-model="user.jobTitle" placeholder="请输入职务"/>
        </uni-forms-item>
        <uni-forms-item label="任现职时间" name="jobTime">
          <uni-datetime-picker type="date" :clear-icon="false" v-model="user.jobTime"
                               @maskClick="maskClick"/>
        </uni-forms-item>
        <uni-forms-item label="进修编号" name="refresherCourseCode" v-if="roleKey=='student'">
          <uni-easyinput v-model="user.refresherCourseCode" placeholder="请输入进修编号"/>
        </uni-forms-item>
        <uni-forms-item label="照片" name="photograph">
          <uni-file-picker fileMediatype="image" mode="grid" @select="select" limit="1" title="最多选择1张图片"
                           v-model="fileList" :value="fileList" file-mediatype="all"></uni-file-picker>
        </uni-forms-item>
      </uni-forms>
      <button type="primary" @click="submit" v-show="roleKey=='student'" :disabled="disabled">提交</button>
    </view>
  </view>
</template>

<script>
import {
  addStuInfo,
  getStuInfo,
  updateStuInfo,
  getteacherInfoByteaId,
  getSysDictDataByDictType
} from "@/api/system/user"
import {
  getApplyByuserId
} from "@/api/jz/apply/info.js"
import {
  getToken,
  getUser,
  getInfoId,
  getInforoleKey,
  setInfoId,
} from '@/utils/auth';
import config from '@/config'

export default {
  data() {
    return {
      disabled: false,
      account: "",
      user: {
        name: "",
        phone: "",
        identityCard: "",
        email: "",
        sex: "",
        photograph: "",
        dateOfBirth: "",
        nation: "",
        nativePlace: "",
        schoolTag: "",
        education: "",
        professionalTitle: "",
        companyName: "",
        partyGroupings: "",
        jobTitle: "",
        refresherCourseCode: "",
        userId: getUser(),
      },
      educationList: [],
      nationList: [],
      sexs: [{
        text: '男',
        value: 0
      }, {
        text: '女',
        value: 1
      }],
      roleKey: getInforoleKey(),
      fileList: [],
      rules: {
        name: {
          rules: [{
            required: true,
            errorMessage: '姓名不能为空'
          }]
        },
        phone: {
          rules: [{
            required: true,
            errorMessage: '手机号码不能为空'
          }, {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            errorMessage: '请输入正确的手机号码'
          }]
        },
        identityCard: {
          rules: [{
            required: true,
            errorMessage: '身份证号码不能为空'
          },
            {
              pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
              errorMessage: '请输入正确证件号码'
            }
          ]
        },
        sex: {
          rules: [{
            required: true,
            errorMessage: '请选择性别'
          }]
        },
        dateOfBirth: {
          rules: [{
            required: true,
            errorMessage: '请选择出生日期'
          }]
        },
        nation: {
          rules: [{
            required: true,
            errorMessage: '请输入民族'
          }]
        },
        nativePlace: {
          rules: [{
            required: true,
            errorMessage: '请输入籍贯'
          }]
        },
        schoolTag: {
          rules: [{
            required: true,
            errorMessage: '请输入毕业学校'
          }]
        },
        education: {
          rules: [{
            required: true,
            errorMessage: '请选择学历'
          }]
        },
        professionalTitle: {
          rules: [{
            required: true,
            errorMessage: '请输入职称'
          }]
        },
        teachSubjects: {
          rules: [{
            required: true,
            errorMessage: '请输入教学课'
          }]
        },
        companyName: {
          rules: [{
            required: true,
            errorMessage: '单位名称'
          }]
        },
        partyGroupings: {
          rules: [{
            required: true,
            errorMessage: '请选择政治面貌'
          }]
        },
        jobTitle: {
          rules: [{
            required: true,
            errorMessage: '请输入职务'
          }]
        },
        jobTime: {
          rules: [{
            required: true,
            errorMessage: '请输入任现职时间'
          }]
        },
        photograph: {
          rules: [{
            required: true,
            errorMessage: '请选择上传照片'
          }]
        },
        // email: {
        // 	rules: [{
        // 		required: true,
        // 		errorMessage: '邮箱地址不能为空'
        // 	}, {
        // 		format: 'email',
        // 		errorMessage: '请输入正确的邮箱地址'
        // 	}]
        // }
      }
    }
  },
  mounted() {
    getApplyByuserId().then(res => {
      if (res.code == 200) {
        this.user.name = res.data.name
        this.account = res.data.account
      }

    })
  },
  onLoad() {
    this.getSysDictDataByDictTypeFun("sys_education_level")
    this.getSysDictDataByDictTypeFun("sys_nation")

    if (this.roleKey == "student") {
      let id = getInfoId();
      if (id) {
        this.getStudentInfo(id)
      }
    } else if (this.roleKey == "teacher") {
      let id = getInfoId();
      if (id) {
        this.getteacherInfoByteaId(id)
      }
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    getSysDictDataByDictTypeFun(dictType) {
      getSysDictDataByDictType(dictType).then(res => {
        if (res.code === 200) {
          for (let i = 0; i < res.data.length; i++) {
            let obj = {};
            obj.text = res.data[i].dictLabel
            obj.value = res.data[i].dictValue
            if (dictType === 'sys_education_level') {
              this.educationList.push(obj)
            }
            if (dictType === 'sys_nation') {
              this.nationList.push(obj)
            }
          }
        }
      })
    },
    maskClick(e) {
    },
    getStudentInfo(id) {
      getStuInfo(id).then(response => {
        if (response.code == 200) {
          this.user = response.data
          this.fileList.push({
            url: this.user.photograph
          })
        }

      })
    },

    getteacherInfoByteaId(id) {
      getteacherInfoByteaId(id).then(response => {
        if (response.code == 200) {
          this.user = response.data
          this.fileList.push({
            url: this.user.photograph
          })
        }

      })
    },
    //图片上传
    select(e) {
      this.disabled = true
      //前端数据请求时，显示加载提示弹框
      uni.showLoading({
        title: '图片正在上传中,请等待'
      });
// 数据从后端接口返回后，提示弹框关闭
      const tempFilePaths = e.tempFilePaths;
      //获取图片临时路径
      const imgUrl = tempFilePaths[0]
      uni.uploadFile({
        //图片上传地址
        url: config.baseUrl + '/system/user/profile/avatar',
        filePath: imgUrl,
        //上传名字，注意与后台接收的参数名一致
        name: 'avatarfile',
        //设置请求头
        header: {
          "Content-Type": "multipart/form-data"
        },
        header: {
          "Authorization": 'Bearer ' + getToken()
        },
        //请求成功，后台返回自己服务器上的图片地址
        success: (uploadFileRes) => {
          let data = JSON.parse(uploadFileRes.data)
          this.user.photograph = config.baseUrl + data.imgUrl
          uni.hideLoading();
          this.disabled = false
          // //处理数据
          // const path = JSON.parse(uploadFileRes.data)
          // //赋值，前端渲染
          // this.baseFormData.photo = path.imgUrl
        }
      });
    },
    submit(ref) {
      this.$refs.form.validate().then(res => {
        if (getInfoId()) {
          updateStuInfo(this.user).then(response => {
            this.$modal.msgSuccess("修改成功")
            uni.navigateBack({
              delta: 1
            });
          })
        } else {
          addStuInfo(this.user).then(response => {

            if (response.code == 200) {

              setInfoId(response.data.id)
              this.$modal.msgSuccess("新增成功")
              uni.navigateBack({
                delta: 1
              });
            }

          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}

.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
}
</style>